package com.jsh.erp.service.print;

import com.jsh.erp.domain.entities.DepotHead;
import com.jsh.erp.domain.entities.DepotItemVo4WithInfoEx;
import com.jsh.erp.domain.entities.Person;
import com.jsh.erp.domain.entities.Supplier;
import com.jsh.erp.domain.vo.ReturnPrintVo;
import com.jsh.erp.domain.vo.SaleOutPrintVo;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.service.accountHead.AccountHeadService;
import com.jsh.erp.service.depotHead.DepotHeadService;
import com.jsh.erp.service.depotItem.DepotItemService;
import com.jsh.erp.service.person.PersonService;
import com.jsh.erp.service.supplier.SupplierService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.NumberToWords;
import com.jsh.erp.utils.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PrintService {

    private Logger logger = LoggerFactory.getLogger(PrintService.class);

    @Autowired
    private DepotHeadService depotHeadService;
    @Autowired
    private DepotItemService depotItemService;
    @Autowired
    private UserService userService;
    @Autowired
    private SupplierService supplierService;
    @Resource
    private AccountHeadService accountHeadService;
    @Resource
    private PersonService personService;


    public SaleOutPrintVo getSaleOutPrintData(Long id) throws Exception {
        DepotHead depotHead = depotHeadService.getDepotHead(id);
        if (depotHead == null) {
            throw new BusinessRunTimeException(500, "can not find bill");
        }
        SaleOutPrintVo saleOutPrintVo = new SaleOutPrintVo();
//        SaleSumAccountHead accountHead = accountHeadService.getAccountHeadBySaleId(depotHead.getId());
        Supplier supplier = supplierService.getSupplier(depotHead.getOrganId());
        if (!StringUtils.isEmpty(depotHead.getSalesMan())) {
            Person person = personService.getPerson(Long.parseLong(depotHead.getSalesMan()));
            saleOutPrintVo.setSalesPerson(person.getName());
        }
        saleOutPrintVo.setPoNo(depotHead.getPono());

        List<DepotItemVo4WithInfoEx> detailList = depotItemService.getDetailList(id);
        List<SaleOutPrintVo.Table> list = new ArrayList<>(detailList.size());
        //saleOutPrintVo.setTable1(list);
        saleOutPrintVo.setTable(list);
        saleOutPrintVo.setBillNo(depotHead.getNumber());
        saleOutPrintVo.setDate(Tools.parseDateToStr(depotHead.getCreateTime()));
        saleOutPrintVo.setPrintBy(userService.getCurrentUser().getUsername());
        saleOutPrintVo.setPrintDate(Tools.parseDateToStr(new Date()));
        saleOutPrintVo.setCustom(supplier.getSupplier() + "  , address: " + supplier.getAddress() + "  , mobile: " + supplier.getPhoneNum());
        if (depotHead.getPayType() == null) {
            saleOutPrintVo.setPayType("");
        } else {
            saleOutPrintVo.setPayType(depotHead.getPayType() == 1 ? "CASH" : "CREDIT");
        }
        String lang = userService.getCurrentUser().getLang();
        float c = 0, a = 0;
        String unitName = "";
        DecimalFormat df = new DecimalFormat("#,##0.00");
        for (int i = 0; i < detailList.size(); i++) {
            DepotItemVo4WithInfoEx depotItem = detailList.get(i);

            if (StringUtils.isEmpty(saleOutPrintVo.getWarehouse())) {
                saleOutPrintVo.setWarehouse(depotItem.getDepotName());
            }

            SaleOutPrintVo.Table item = new SaleOutPrintVo.Table();
            item.setId(i + 1);
            if ("en_US".equals(lang)) {
                item.setName(depotItem.getMEnName() + "-" + depotItem.getMModel());
            } else {
                item.setName(depotItem.getMName() + "-" + depotItem.getMModel());
            }

            item.setCode(depotItem.getBarCode());
            item.setNo(depotItem.getBasicNumber().setScale(2, RoundingMode.HALF_UP).floatValue());
            item.setUnit(depotItem.getMaterialUnit());
            if (depotItem.getUnitPrice() != null) {
                item.setListPrice(depotItem.getUnitPrice().floatValue());
                item.setPrice(depotItem.getUnitPrice().floatValue());
            }
            if (depotItem.getDiscount() == null) {
                item.setDiscount("0%");
            } else {
                item.setDiscount(depotItem.getDiscount().stripTrailingZeros().toPlainString() + "%");
            }
            if (depotItem.getDiscountMoney() == null || depotItem.getDiscountMoney().floatValue() == 0f) {
                item.setAmount(depotItem.getAllPrice().floatValue());
            } else {
                String formattedAmount = df.format(depotItem.getDiscountMoney());
                item.setAmount(Float.parseFloat(formattedAmount.replace(",", "")));
                //item.setAmount(depotItem.getDiscountMoney().floatValue());
            }
            list.add(item);
            c = c + item.getNo();
            a = a + item.getAmount();
            if (StringUtils.isEmpty(unitName) && depotItem.getMaterialUnit() != null) {
                unitName = depotItem.getMaterialUnit();
            }
        }
        String formattedAmount = df.format(a);
        saleOutPrintVo.setTotal("Grand Total:   " + c + "       " + unitName + "      " + formattedAmount);
        saleOutPrintVo.setTotalEn("LKR " + NumberToWords.convertToWords(a));
        return saleOutPrintVo;
    }

    public ReturnPrintVo getReturnPrintData(Long id) throws Exception {
        DepotHead depotHead = depotHeadService.getDepotHead(id);
        if (depotHead == null) {
            throw new BusinessRunTimeException(500, "can not find bill");
        }
//        SaleSumAccountHead accountHead = accountHeadService.getAccountHeadBySaleId(depotHead.getId());
        List<DepotItemVo4WithInfoEx> detailList = depotItemService.getDetailList(id);
        ReturnPrintVo returnPrintVo = new ReturnPrintVo();
        returnPrintVo.setSaleReturnNo(depotHead.getNumber());
        returnPrintVo.setSaleReturnDate(Tools.parseDateToStr(depotHead.getCreateTime()));
        returnPrintVo.setInvNo(depotHead.getLinkNumber());
        returnPrintVo.setPrintBy(userService.getCurrentUser().getUsername());
        returnPrintVo.setPrintDate(Tools.parseDateToStr(new Date()));
        DepotHead linkDepotHead = depotHeadService.getByNumber(depotHead.getLinkNumber());
        if (linkDepotHead != null) {
            returnPrintVo.setInvoiceDate(Tools.parseDateToStr(linkDepotHead.getCreateTime()));
        }
        returnPrintVo.setReasonForReturn(depotHead.getRemark());
        returnPrintVo.setAse("");
        returnPrintVo.setSeContactNo("");
        Supplier supplier = supplierService.getSupplier(depotHead.getOrganId());
        returnPrintVo.setCustomerContactNo(supplier.getSupplier() + "  , address: " + supplier.getAddress() + "  , mobile: " + supplier.getPhoneNum());
        if (!StringUtils.isEmpty(depotHead.getSalesMan())) {
            Person person = personService.getPerson(Long.parseLong(depotHead.getSalesMan()));
            if (person != null) {
                returnPrintVo.setSalesExecutive(person.getName());
            }
        }
        List<ReturnPrintVo.Table> list = new ArrayList<>(detailList.size());
        returnPrintVo.setTable(list);
        String lang = userService.getCurrentUser().getLang();
        float c = 0, a = 0;
        String unitName = "";
        for (int i = 0; i < detailList.size(); i++) {
            DepotItemVo4WithInfoEx depotItem = detailList.get(i);
            ReturnPrintVo.Table item = new ReturnPrintVo.Table();
            item.setId(i + 1);
            if ("en_US".equals(lang)) {
                item.setName(depotItem.getMEnName() + "-" + depotItem.getMModel());
            } else {
                item.setName(depotItem.getMName() + "-" + depotItem.getMModel());
            }

            item.setCode(depotItem.getBarCode());
            item.setNo(depotItem.getBasicNumber().setScale(2, RoundingMode.HALF_UP).floatValue());
            item.setUnit(depotItem.getMaterialUnit());
//            item.setListPrice(depotItem.getUnitPrice().floatValue());
            item.setPrice(depotItem.getUnitPrice().floatValue());
//            if (depotItem.getDiscount() == null) {
//                item.setDiscount("0%");
//            } else {
//                item.setDiscount(depotItem.getDiscount() + "%");
//            }
            if (depotItem.getDiscountMoney() == null || depotItem.getDiscountMoney().floatValue() == 0f) {
                item.setAmount(depotItem.getAllPrice().floatValue());
            } else {
                item.setAmount(depotItem.getDiscountMoney().floatValue());
            }
            list.add(item);
            c = c + item.getNo();
            a = a + item.getAmount();
            if (StringUtils.isEmpty(unitName) && depotItem.getUnitName() != null) {
                unitName = depotItem.getUnitName();
            }
        }
        returnPrintVo.setTotal("Grand Total:   &nbsp;&nbsp;&nbsp;&nbsp;" + c + "     " + unitName + "      " + a);
        returnPrintVo.setTotalEn("LKR " + NumberToWords.convertToWords(a));
        return returnPrintVo;
    }
}
